<template>
  <div>

    <div class="container">
      <!--分列-->
      <div class="box" v-for="item in columns" :key="item + '列'">
        <!--每列的数据-->
        <div class="item" v-for="(a,index) in essayItem[item - 1]" :key="index + '子项' + item" >
          <img :src="a.img" alt="配图">
          <div class="content">{{a.essay}}</div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  export default {
    name: "myEssay",
    data() {
      return {
        //获取的屏幕宽度
        nowScreenWidth: document.documentElement.clientWidth
      }
    },
    computed: {
      // 根据屏幕宽度计算行数
      columns() {
        let i = this.nowScreenWidth
        // console.log(i);
        if(i >= 1200){
          return 4
        }
        else if (1200 > i && i >=  720){
          return 3
        }
        else if (720 > i && i >= 480){
          return 2
        }
        else {
          return 1
        }
      },

      //演示数据
      allEssay() {
        // 总的数据
        let items = [];
        for(let i = 0; i < 20; i++){
          // console.log('循环');
          items.push({
            img: this.$store.state.userImg,
            essay: '第' + i + '个' + this.$store.state.userSignature
          })
        }
        //这时items是总的数据
        // console.log(items);
        return items
      },

      //把数据分列排序
      essayItem() {
        // 按列划分的数据
        let itemsOfColumn =[];

        // 把总的数据根据行数和下标进行过滤
        for(let j = 0; j < this.columns; j++){
          itemsOfColumn.push(this.allEssay.filter((item,index) => index % this.columns === j))
          // console.log(itemsOfColumn)
        }
        return itemsOfColumn
      }
    },
    watch: {
    },
    filters: {
    },
    methods: {
    },
    beforeCreate() {
    },
    mounted() {
      //监听屏幕宽度变化
      const that = this
      window.addEventListener("resize", function() {
        return (() => {
          window.screenWidth= document.body.clientWidth;
          that.nowScreenWidth= window.screenWidth;
        })();
      });
    }
  }
</script>

<style lang="less" scoped>
  @import "~@/styles/views/defaultValue.less";
  @import "~@/styles/views/styleAndAnimation.less";

  /*会自动适应宽度，不需要额外的配置，需要刷新页面进行重置个数，不会自动调整，后面试一下*/
  /*根据屏幕变化自动划分列数已添加*/
  .container {
    display: flex;
    flex-wrap: wrap;
    background: @areaBackground;

    .box {
      flex: 1;

      .item {
        margin: 10px;
        border-radius: @borderRadius * 2;
        overflow: hidden;
        background: @itemBackgroundColor;

        img {
          width: 100%;
        }

        .content {
          margin: 20px;
        }
      }
    }
  }
</style>